import createjs from "createjs-ts";
import cjs=createjs
import BaseView from "./BaseView";
import { getRadian } from "../utils/MathTools";
import Bubble from "../display/Bubble";

export default class MainView extends BaseView {
  private arr:Bubble[]=[]
  //圆圈半径
  private radius=50
  constructor() {
    super();
    for (let i = 0; i < 20; i++) {
      this.addOne()
    }
    //this.hitTestAllShape()
    this.on("tick",()=>{
      this.hitTestAllShape2()
      //对所有圆进行碰撞检测
      this.hitTestAllShape()
      //更新所有圆圈的受力
      this.updateAllJoinForces()
    })
  }
  /**
   * 添加一个圆形
   */
  addOne():void {
    const shape=new Bubble(20+Math.random()*30)
    //this.drawShape(shape)
    shape.setTransform(100+Math.random()*600, 100+Math.random()*400, 1, 1)
    this.addChild(shape)
    this.arr.push(shape)
  }
  /**
   * 更新所有圆圈的受力
   */
  private updateAllJoinForces():void {
    for (let i = 0; i < this.arr.length; i++) {
      const b=this.arr[i]
      b.updateJoinForces()
      b.clear()
   }
  }
  /** 对所有圆形进行碰撞检测，并记录受力 */
  protected hitTestAllShape():void {
    for (let i = 0; i < this.arr.length; i++) {
      const c0=this.arr[i]
      for (let j = i+1; j < this.arr.length; j++) {
        const c1=this.arr[j]
        //console.log(i,j)
        const d=this.hitTestShape(c0,c1)
        if(d<-0.1){
          c0.addForce(d,getRadian(c0,c1))
          c1.addForce(d,getRadian(c1,c0))
        }
      }
    }
  }
  /** 对所有圆形进行边界约束 */
  protected hitTestAllShape2():void {
    for (let i = 0; i < this.arr.length; i++) {
      const c0=this.arr[i]
      if(c0.x<c0.radius){
        //c0.addForce(c0.radius-c0.x,getRadian({x:0,y:c0.y},c0))
        c0.x=c0.radius
      }
      if(c0.y<c0.radius){
        //c0.addForce(c0.radius-c0.y,getRadian({x:c0.x,y:0},c0))
        c0.y=c0.radius
      }
      if(c0.x>(this.width-c0.radius)){
        //c0.addForce(c0.x+c0.radius-this.width,getRadian({x:this.width,y:c0.y},c0))
        c0.x=this.width-c0.radius
      }
      if(c0.y>(this.height-c0.radius)){
        //c0.addForce(c0.y+c0.radius-this.height,getRadian({x:c0.x,y:this.height},c0))
        c0.y=this.height-c0.radius
      }
    }
  }
  /**
   * 碰撞检测
   * @param c0 圆形对象
   * @param c1 圆形对象
   * @returns true/false
   */
  private hitTestShape(c0:Bubble,c1:Bubble):number{
    const a=Math.abs(c0.x-c1.x),b=Math.abs(c0.y-c1.y)
    const c=a*a+b*b
    //console.log(c)
    const r=Math.sqrt(c)
    return r-(c0.radius+c1.radius)
  }
}